package org.yyj.dao.impl;

import org.yyj.dao.KcDao;
import org.yyj.factory.*;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import org.yyj.model.Kcb;

import java.util.List;

public class KcDaoImp implements KcDao {
    @Override
    //查询某门课程信息
    public Kcb getOneKc(String kch) {
        try {
            //创建Configuration
            Configuration configuration=new
                    Configuration().configure("hibernate.cfg.xml");
            //获取SessionFactory
            SessionFactory sessionFactory=configuration.buildSessionFactory();
            //获取Session
            Session session=sessionFactory.openSession();
           /* Session session= HibernateFactory.getSession();*/
            //开启事务
            Transaction transaction=session.beginTransaction();
            Query query=session.createQuery("from Kcb where kch=?");
            query.setParameter(0,kch);
            query.setMaxResults(1);
            Kcb kcb=(Kcb) query.uniqueResult();     //执行查询结果
            transaction.commit();
            session.clear();            //清除缓存
            return kcb;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }

    @Override
    //查询所有课程信息
    public List getAll() {
        try {
            /*//创建Configuration
            Configuration configuration=new
                    Configuration().configure("hibernate.cfg.xml");
            //获取SessionFactory
            SessionFactory sessionFactory=configuration.buildSessionFactory();
            //获取Session
            Session session=sessionFactory.openSession();*/
            Session session= HibernateSessionFactory.getSession();
            //开启事务
            Transaction transaction=session.beginTransaction();
            //执行查询结果
            List list=session.createQuery("from Kcb order by kch").list();
            transaction.commit();
            return list;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
